package com.xhh.learning.record.algorithm.sort;

import io.lettuce.core.ValueScanCursor;

/**
 * 类名： BinarySearch1
 * 描述：
 * 公司： 北京海鑫科金高科技股份有限公司
 * 作者： Administrator
 * 版本： V1.0
 * 创建时间:  2019/4/15 16:39
 * 最后修改时间:  2019/4/15 16:39
 */
public class BinarySearch1 {

    public static void main(String[] args) {
        int[] arr = {5, 1, 3};

        int bsearch = bsearch(arr, arr.length - 1, 5);
        System.out.println(bsearch);
    }


    static int bsearch(int[] nums, int n, int target) {
        int low = 0, high = nums.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] > target) {
                if (nums[low] <= target) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            } else if (nums[mid] < target) {
                if (nums[high] >= target) {
                    low = mid + 1;
                } else {
                    high--;
                    if (nums[low] == target) {
                        return low;
                    }
                    low = mid;
                }
            } else {
                return mid;
            }
        }

        return -1;
    }
}
